package com.wm.blog_gateway.auth;

import com.alibaba.fastjson.JSONObject;
import com.wm.blog_common.result.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/***
 * @ClassName: AuthFailureHandler
 * @Description: 校验失败
 * @Author: 半卷流年
 * @Create_time: 18:44 2020-3-30
 */
@Component
public class AuthFailureHandler implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        if (exception instanceof UsernameNotFoundException) {
            return writeErrorMessage(response, "用户不存在");
        } else if (exception instanceof BadCredentialsException) {
            return writeErrorMessage(response, "密码错误");
        } else if (exception instanceof LockedException) {
            return writeErrorMessage(response,"用户被锁定");
        }
        return writeErrorMessage(response,"服务繁忙，庆稍后重试。。。");
    }

    private Mono<Void> writeErrorMessage(ServerHttpResponse response,String msg) {
        Result result = Result.failure();
        result.setMsg(msg);
        String r = JSONObject.toJSONString(result);
        DataBuffer buffer = null;
        try {
            buffer = response.bufferFactory().wrap(r.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));
    }
}
